package com.tj.jinzao.widgets;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.tj.jinzao.R;
import com.tj.jinzao.manager.AudioManager;


/**
 * 语音输入按钮
 * Created by wjy on 2015/11/29.
 */
public class AudioRecordButton extends AppCompatButton {

    private static final int STATE_NORMAL = 1;// 默认的状态
    private static final int STATE_RECORDING = 2;// 正在录音
    private static final int STATE_WANT_TO_CANCEL = 3;// 希望取消

    private int mCurrentState = STATE_NORMAL; // 当前的状态
    private boolean mRecording = false;// 已经开始录音

    private static final int DISTANCE_Y_CANCEL = 50;

    private AudioManager mAudioManager;

    private float mTime;
    // 是否触发longClick
    private boolean mReady;

    private static final int MSG_AUDIO_PREPARED = 0x110;
    private static final int MSG_VOICE_CHANGED = 0x111;
    private static final int MSG_DIALOG_DISMISS = 0x112;
    private static final int MSG_DIALOG_CANCEL = 0x113;
    /*
     * 获取音量大小的线程
     */
    private Runnable mGetVoiceLevelRunnable = new Runnable() {

        public void run() {
            while (mRecording) {
                try {
                    Thread.sleep(100);
                    mTime += 0.1f;
                    mHandler.sendEmptyMessage(MSG_VOICE_CHANGED);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_AUDIO_PREPARED:
                    // 显示对话框在开始录音以后
                    showRecordingDialog();
                    mRecording = true;
                    // 开启一个线程
                    new Thread(mGetVoiceLevelRunnable).start();
                    break;

                case MSG_VOICE_CHANGED:
                    updateVoiceLevel(mAudioManager.getVoiceLevel(7));
                    break;
                case MSG_DIALOG_DISMISS:
                    dismissDialog();
                    break;
                case MSG_DIALOG_CANCEL:
                    setBackgroundResource(R.drawable.btn_speak_normal);
                    mAudioManager.cancel();
                    dismissDialog();
                    reset();
                    break;

            }
            return true;
        }
    });

    /**
     * 以下2个方法是构造方法
     */
    public AudioRecordButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        mAudioManager = AudioManager.getInstance();
        mAudioManager.setOnAudioStateListener(new AudioManager.AudioStateListener() {

            public void wellPrepared() {
                mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
            }
        });

        // 由于这个类是button所以在构造方法中添加监听事件
        setOnLongClickListener(new OnLongClickListener() {

            public boolean onLongClick(View v) {
                mReady = true;

                mAudioManager.prepareAudio();

                return false;
            }
        });
    }

    public AudioRecordButton(Context context) {
        this(context, null);
    }

    /**
     * 录音完成后的回调
     */
    public interface AudioFinishRecorderListener {
        void onFinish(float seconds, String filePath);

    }

    private AudioFinishRecorderListener mAudioFinishListener;

    public void setAudioFinishListener(AudioFinishRecorderListener listener) {
        mAudioFinishListener = listener;
    }

    /**
     * 屏幕的触摸事件
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();
        int x = (int) event.getX();// 获得x轴坐标
        int y = (int) event.getY();// 获得y轴坐标

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                changeState(STATE_RECORDING);
                setBackgroundResource(R.drawable.btn_speak_pressed);
                break;
            case MotionEvent.ACTION_MOVE:
                if (mRecording) {
                    // 如果想要取消，根据x,y的坐标看是否需要取消
                    if (wantToCancle(x, y)) {
                        changeState(STATE_WANT_TO_CANCEL);
                    } else {
                        changeState(STATE_RECORDING);
                    }
                }

                break;
            case MotionEvent.ACTION_UP:
                setBackgroundResource(R.drawable.btn_speak_normal);
                if (!mReady) {
                    reset();
                    return super.onTouchEvent(event);
                }
                if (!mRecording || mTime < 1.5f) {
                    tooShort();
                    mAudioManager.cancel();
                    mHandler.sendEmptyMessageDelayed(MSG_DIALOG_DISMISS, 1000);// 延迟显示对话框
                } else if (mCurrentState == STATE_RECORDING) { // 正在录音的时候，结束
                    dismissDialog();
                    mAudioManager.release();

                    if (mAudioFinishListener != null) {
                        mAudioFinishListener.onFinish(mTime, mAudioManager.getCurrentFilePath());
                    }

                } else if (mCurrentState == STATE_WANT_TO_CANCEL) { // 想要取消
                    dismissDialog();
                    mAudioManager.cancel();
                }
                reset();
                break;
            case MotionEvent.ACTION_CANCEL:
                mHandler.sendEmptyMessageDelayed(MSG_DIALOG_CANCEL, 1000);// 延迟取消对话
                break;

        }
        return super.onTouchEvent(event);
    }

    /**
     * 恢复状态及标志位
     */
    private void reset() {
        mRecording = false;
        mTime = 0;
        mReady = false;
        changeState(STATE_NORMAL);
    }

    private boolean wantToCancle(int x, int y) {
        if (x < 0 || x > getWidth()) { // 超过按钮的宽度
            return true;
        }
        // 超过按钮的高度
        if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
            return true;
        }

        return false;
    }

    /**
     * 改变
     */
    private void changeState(int state) {
        if (mCurrentState != state) {
            mCurrentState = state;
            switch (state) {
                case STATE_NORMAL:
//                    setText(R.string.str_recorder_normal);
                    break;

                case STATE_RECORDING:
//                    setBackgroundResource(R.drawable.btn_recorder_recording);
//                    setText(R.string.str_recorder_recording);
                    if (mRecording) {
                        recording();
                    }
                    break;

                case STATE_WANT_TO_CANCEL:
//                    setBackgroundResource(R.drawable.btn_recorder_recording);
//                    setText(R.string.str_recorder_want_cancel);

                    wantToCancel();
                    break;
            }
        }
    }

    private ImageView mIcon;
    private TextView mLabel;

    private Dialog dialog;//用于取消AlertDialog.Builder

    // 显示录音的对话框
    public void showRecordingDialog() {
        if (dialog == null) {
            dialog = new Dialog(getContext(), R.style.ThemeRequestDialog);
            LayoutInflater inflater = LayoutInflater.from(getContext());
            View view = inflater.inflate(R.layout.dialog_recorder_layout, null);
            dialog.setContentView(view);
            mIcon =  view.findViewById(R.id.id_recorder_dialog_icon);
            mLabel = view.findViewById(R.id.id_recorder_dialog_label);
        }
        dialog.show();
//        dialog = builder.show();
    }

    public void recording() {
        if (dialog != null && dialog.isShowing()) { //显示状态
            mIcon.setVisibility(View.VISIBLE);
            mLabel.setVisibility(View.VISIBLE);
            mIcon.setImageResource(R.drawable.audio_record_0);
            mLabel.setText("手指上滑取消发送");
            mLabel.setBackgroundColor(getResources().getColor(R.color.transparent));
        }
    }

    // 显示想取消的对话框
    public void wantToCancel() {
        if (dialog != null && dialog.isShowing()) { //显示状态
            mIcon.setVisibility(View.VISIBLE);
            mLabel.setVisibility(View.VISIBLE);

            mIcon.setImageResource(R.drawable.audio_record_cancel);
            mLabel.setText("松开手指取消发送");
            mLabel.setBackgroundColor(Color.parseColor("#dc1238"));
        }
    }

    // 显示时间过短的对话框
    public void tooShort() {
        if (dialog != null && dialog.isShowing()) { //显示状态
            mIcon.setVisibility(View.VISIBLE);
            mLabel.setVisibility(View.VISIBLE);
            mLabel.setText("录音时间过短");
        }
    }

    // 显示取消的对话框
    public void dismissDialog() {
        if (dialog != null && dialog.isShowing()) { //显示状态
            dialog.dismiss();
            dialog = null;
        }
    }

    // 显示更新音量级别的对话框
    public void updateVoiceLevel(int level) {
        if (dialog != null && dialog.isShowing()) { //显示状态
            if (mCurrentState != STATE_WANT_TO_CANCEL) {
                int resId = R.drawable.audio_record_0;
                //设置图片的id
                switch (level) {
                    case 1:
                        resId = R.drawable.audio_record_1;
                        break;
                    case 2:
                        resId = R.drawable.audio_record_2;
                        break;
                    case 3:
                        resId = R.drawable.audio_record_3;
                        break;
                }
                mIcon.setImageResource(resId);
            }
        }
    }
}
